package com.sky.websocket;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Component
@ServerEndpoint("/ws/{sid}")
public class WebSocketServer {
    //存放会话集合
    private static Map<String, Session> sessionMap = new HashMap<>();
    //连接成功
    @OnOpen
    public void onOpen(Session session, @PathParam("sid")String sid){
        log.info("建立连接:{}",session,sid);
        sessionMap.put(sid,session);
    }
    //客户端消息
    @OnMessage
    public void onMessage(String onMessage,@PathParam("sid")String sid){
        log.info("收到来自：{}",sid+"的消息：{}",onMessage);

    }
    //关闭连接
    @OnClose
    public void onClose(@PathParam("sid")String sid){
        log.info("断开链接：{}",sid);
        sessionMap.remove(sid);
    }
    //群发
    public void sendToAllClient(String message){

        Collection<Session> sessions = sessionMap.values();
        for (Session session : sessions) {
            try {
                session.getBasicRemote().sendText(message);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    //


}
